package com.cc.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mp 字段自动填充
 * @author zhanghaibin
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        Object loginId = StpUtil.getLoginIdDefaultNull();
        if(loginId!=null){
            this.strictInsertFill(metaObject, "createBy", String.class,  loginId.toString());
            this.strictInsertFill(metaObject, "updateBy", String.class,  loginId.toString());
        }else{
            this.strictInsertFill(metaObject, "createBy", String.class,"自行注册");
            this.strictInsertFill(metaObject, "updateBy", String.class,"自行注册");
        }
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        //获取更新者
        Object loginId = StpUtil.getLoginIdDefaultNull();
        if(loginId!=null){
            this.strictInsertFill(metaObject, "updateBy", String.class,loginId.toString());
        }
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}
